package com.yiwenup.leetcode.site;

/**
 * 文件描述
 *
 * @Project struct-algorithm
 * @Package com.yiwenup.leetcode.site
 * @Author yiwenup
 * @Date 2024-12-08 16:59:42
 * @Description https://leetcode.cn/problems/squares-of-a-sorted-array/description/
 * <pre>
 *     给你一个按 非递减顺序 排序的整数数组 nums，返回 每个数字的平方 组成的新数组，要求也按 非递减顺序 排序。
 * </pre>
 * <pre>
 *     输入：nums = [-4,-1,0,3,10]
 *     输出：[0,1,9,16,100]
 *     解释：平方后，数组变为 [16,1,0,9,100]
 *     排序后，数组变为 [0,1,9,16,100]
 * </pre>
 * <pre>
 *     输入：nums = [-7,-3,2,3,11]
 *     输出：[4,9,9,49,121]
 * </pre>
 * <pre>
 *     1 <= nums.length <= 104
 *     -104 <= nums[i] <= 104
 *     nums 已按 非递减顺序 排序
 * </pre>
 */
public class No0977 {
    public int[] sortedSquares(int[] nums) {
        int[] res = new int[nums.length];
        int k = res.length - 1;

        int left = 0;
        int right = nums.length - 1;

        while(left <= right) {
            int leftSqrt = nums[left] * nums[left];
            int rightSqrt = nums[right] * nums[right];
            if(leftSqrt <= rightSqrt) {
                res[k] = rightSqrt;
                right--;
            } else {
                res[k] = leftSqrt;
                left++;
            }
            k--;
        }

        return res;
    }
}
